"""
用户认证视图模块（Session 认证 - 备用）
提供用户登录、注册、获取用户信息等接口
"""
from django.contrib.auth import authenticate, login, logout, get_user_model
from django.contrib.auth.hashers import make_password
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.http import JsonResponse
import json

User = get_user_model()


def success_response(data=None, message="操作成功"):
    """成功响应"""
    return JsonResponse({
        'code': 200,
        'message': message,
        'data': data
    })


def error_response(message="操作失败", code=400):
    """错误响应"""
    return JsonResponse({
        'code': code,
        'message': message,
        'data': None
    }, status=code)


@csrf_exempt
@require_http_methods(["POST"])
def login_view(request):
    """
    用户登录接口
    POST /creation/auth/login
    请求参数:
    {
        "username": "用户名",
        "password": "密码"
    }
    """
    try:
        data = json.loads(request.body)
        username = data.get('username')
        password = data.get('password')
        
        if not username or not password:
            return error_response("用户名和密码不能为空")
        
        # 认证用户
        user = authenticate(request, username=username, password=password)
        
        if user is not None:
            # 登录成功
            login(request, user)
            
            return success_response({
                'user_id': user.id,
                'username': user.username,
                'email': user.email,
                'is_staff': user.is_staff,
                'session_id': request.session.session_key
            }, "登录成功")
        else:
            return error_response("用户名或密码错误", 401)
            
    except json.JSONDecodeError:
        return error_response("请求参数格式错误", 400)
    except Exception as e:
        return error_response(f"登录失败: {str(e)}", 500)


@csrf_exempt
@require_http_methods(["POST"])
def register_view(request):
    """
    用户注册接口
    POST /creation/auth/register
    请求参数:
    {
        "username": "用户名",
        "password": "密码",
        "email": "邮箱"
    }
    """
    try:
        data = json.loads(request.body)
        username = data.get('username')
        password = data.get('password')
        email = data.get('email', '')
        
        if not username or not password:
            return error_response("用户名和密码不能为空")
        
        # 检查用户名是否已存在
        if User.objects.filter(username=username).exists():
            return error_response("用户名已存在", 400)
        
        # 检查邮箱是否已存在
        if email and User.objects.filter(email=email).exists():
            return error_response("邮箱已被注册", 400)
        
        # 创建用户
        user = User.objects.create(
            username=username,
            email=email,
            password=make_password(password)
        )
        
        # 自动登录
        login(request, user)
        
        return success_response({
            'user_id': user.id,
            'username': user.username,
            'email': user.email,
            'session_id': request.session.session_key
        }, "注册成功")
        
    except json.JSONDecodeError:
        return error_response("请求参数格式错误", 400)
    except Exception as e:
        return error_response(f"注册失败: {str(e)}", 500)


@csrf_exempt
@require_http_methods(["POST"])
def logout_view(request):
    """
    用户登出接口
    POST /creation/auth/logout
    """
    try:
        logout(request)
        return success_response(message="登出成功")
    except Exception as e:
        return error_response(f"登出失败: {str(e)}", 500)


@csrf_exempt
@require_http_methods(["GET"])
def info_view(request):
    """
    获取当前登录用户信息接口
    GET /creation/auth/info
    """
    try:
        if not request.user.is_authenticated:
            return error_response("未登录", 401)
        
        user = request.user
        return success_response({
            'user_id': user.id,
            'username': user.username,
            'email': user.email,
            'is_staff': user.is_staff,
            'is_superuser': user.is_superuser,
            'date_joined': user.date_joined.strftime('%Y-%m-%d %H:%M:%S'),
            'last_login': user.last_login.strftime('%Y-%m-%d %H:%M:%S') if user.last_login else None
        })
        
    except Exception as e:
        return error_response(f"获取用户信息失败: {str(e)}", 500)


@csrf_exempt
@require_http_methods(["POST"])
def update_profile(request):
    """
    更新用户信息接口
    POST /creation/auth/update
    请求参数:
    {
        "email": "新邮箱"  (可选)
    }
    """
    try:
        if not request.user.is_authenticated:
            return error_response("未登录", 401)
        
        data = json.loads(request.body)
        user = request.user
        
        # 更新邮箱
        email = data.get('email')
        if email:
            # 检查邮箱是否已被其他用户使用
            if User.objects.filter(email=email).exclude(id=user.id).exists():
                return error_response("邮箱已被其他用户使用", 400)
            user.email = email
        
        user.save()
        
        return success_response({
            'user_id': user.id,
            'username': user.username,
            'email': user.email
        }, "更新成功")
        
    except json.JSONDecodeError:
        return error_response("请求参数格式错误", 400)
    except Exception as e:
        return error_response(f"更新失败: {str(e)}", 500)


@csrf_exempt
@require_http_methods(["POST"])
def change_password(request):
    """
    修改密码接口
    POST /creation/auth/change-password
    请求参数:
    {
        "old_password": "旧密码",
        "new_password": "新密码"
    }
    """
    try:
        if not request.user.is_authenticated:
            return error_response("未登录", 401)
        
        data = json.loads(request.body)
        old_password = data.get('old_password')
        new_password = data.get('new_password')
        
        if not old_password or not new_password:
            return error_response("旧密码和新密码不能为空")
        
        user = request.user
        
        # 验证旧密码
        if not user.check_password(old_password):
            return error_response("旧密码错误", 400)
        
        # 设置新密码
        user.set_password(new_password)
        user.save()
        
        # 重新登录
        login(request, user)
        
        return success_response(message="密码修改成功")
        
    except json.JSONDecodeError:
        return error_response("请求参数格式错误", 400)
    except Exception as e:
        return error_response(f"修改密码失败: {str(e)}", 500)
